import mimetypes
import os
import smtplib
from email.message import EmailMessage


def sendEmail(receiver_email):
    # 你的邮箱地址和密码
    sender_email = 'lidaoyu_work@163.com'
    sender_password = 'BUQQAIHXBPSPPTCI'

    subject = '测试邮件'
    body = '这是一封测试邮件。'

    # 创建邮件对象
    message = EmailMessage()
    message['From'] = sender_email
    message['To'] = receiver_email
    message['Subject'] = subject

    message.set_content(body)

    # html内容
    message.add_alternative("""\
    <!DOCTYPE html>
    <html>
        <body>
            <h1 style="color:Orange;">这是一封测试邮件。</h1>
        </body>
    </html>
    """, subtype='html')

    attachment_path = '数据/dataset.xls'  # 添加附件
    file_name = os.path.basename(attachment_path)  # 提取文件名
    mime_type, encoding = mimetypes.guess_type(attachment_path)  # 获取文件MIME类型
    maintype = mime_type.split('/')[0]
    subtype = mime_type.split('/')[1]
    with open(attachment_path, 'rb') as f:
        filedata = f.read()
    message.add_attachment(filedata, maintype, subtype, filename=file_name)

    # 使用SMTP服务器发送邮件
    with smtplib.SMTP('smtp.163.com') as server:
        server.starttls()  # 使用TLS加密连接
        server.login(sender_email, sender_password)  # 登录邮箱
        server.send_message(message)  # 发送邮件

    print('邮件发送成功')


if __name__ == '__main__':
    receiver_emails = '1257800527@qq.com'
    sendEmail(receiver_emails)
